package com.myself.ssoserver.service

import com.myself.ssoserver.entity.User
import org.redisson.api.RedissonClient
import org.slf4j.LoggerFactory
import org.springframework.stereotype.Service
import java.time.Duration

// 用户注册服务
@Service
open class RegistrationService(
    private val emailService: EmailService,
    private val emailRateLimitService: EmailRateLimitService
) {
    open fun sendVerificationEmail(user: User) {
        val variables = mapOf(
            "user" to user,
            "expireTime" to "24小时"
        )
        if (emailRateLimitService.checkSendRate(user.email))
            emailService.sendHtmlEmail(
                to = user.email,
                subject = "请验证您的邮箱",
                template = "verification",
                variables = variables
            )

        }

}


@Service
open class EmailRateLimitService(
    private val redissonClient: RedissonClient
) {
    private val logger = LoggerFactory.getLogger(javaClass)

   open fun checkSendRate(email: String): Boolean {
        val key = "email:rate:limit:$email"
        val count = redissonClient.getAtomicLong(key)

        return when {
            count.get() >= 5 -> {
                logger.warn("邮件发送过于频繁: $email")
                false
            }
            else -> {
                count.incrementAndGet()
                count.expire(Duration.ofHours(1))
                true
            }
        }
    }
}